#!/bin/bash
###
# @Author: admin@attacker.club
# @Date: 2023-03-16 16:57:09
# @LastEditTime: 2024-08-07 15:15:57
# @Description: Pro 清理
###
# rm /opt/disk_clean.sh -f ; wget -P /opt http://wuyou.run/scripts/tools/disk/clean.sh ;chmod 750 /opt/clean.sh
# */15 * * * *  /opt/clean.sh

## 清理磁盘空间
function clean() {

    echo "开始清理磁盘空间"
    journalctl --vacuum-size=50M

    if [ -d /home ]; then
        find /home -name "nohup.out" -exec sh -c 'echo > {}' \;
        find /home -name "*2*.log" -mtime +3 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
        find /home -type f -name "*.log" -size +10G -exec sh -c 'echo "" > "{}"' \;
    fi
    if [ -d /data ]; then
        find /data -name "nohup.out" -exec sh -c 'echo > {}' \;
        find /data -name "*2*.log" -mtime +3 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
        find /data -type f -name "*.log" -size +10G -exec sh -c 'echo "" > "{}"' \;
    fi
    if [ -d /var ]; then
        find /data -name "nohup.out" -exec sh -c 'echo > {}' \;
        find /data -name "*2*.log" -mtime +3 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
        find /data -type f -name "*.log" -size +10G -exec sh -c 'echo "" > "{}"' \;
    fi
    if [ -f /var/spool/mail/root ]; then
        echo >/var/spool/mail/root
    fi
    if [ -f /var/log/messages ]; then
        echo >/var/log/messages
        rm /var/log/*20* -f
    fi
    if [ -d /var/lib/docker/containers ]; then
        # 清空 Docker 日志文件而不删除；echo -n > 重定向不残留换行符
        find /var/lib/docker/containers -name "*-json.log" -type f -exec sh -c 'echo -n > "{}"' \;
    fi
    if [ -d /var/atlassian/application-data/confluence/backups ]; then
        find /var/atlassian/application-data/confluence/backups -name "backup-*.zip" -mtime +1 -type f -print -exec rm -f {} \; >>/tmp/delete.log 2>&1
    fi

}

## 检查磁盘使用率是否超过 75%
num=$(df -h | awk -F"[ %]+" '/[0-9]/  { if ($5>=75) print $5,$6}' | wc -l)
if [ $num != 0 ]; then
    clean
else
    echo "磁盘空闲"
fi
